<template>
    <div class="design_container">
        <el-card class="card_draggable">
            <el-row v-if="type === 'draggable'">
                <el-col :span="24" class="rect-printElement-types hiprintEpContainer">
                    <el-row class="drag_item_title">拖拽组件列表</el-row>
                    <el-row style="height: 100px;">
                        <el-col :span="12" class="drag_item_box">
                            <div>
                                <a class="ep-draggable-item" tid="defaultModule.text" style>
                                    <span class="glyphicon glyphicon-text-width" ariel-hidden="true"></span>
                                    <p class="glyphicon-class">文本</p>
                                </a>
                            </div>
                        </el-col>
                        <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                            <div>
                                <a class="ep-draggable-item" tid="defaultModule.image" style>
                                    <span class="glyphicon glyphicon-picture" ariel-hidden="true"></span>
                                    <p class="glyphicon-class">图片</p>
                                </a>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row style="height: 100px;">
                        <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                            <div>
                                <a class="ep-draggable-item" tid="defaultModule.longText">
                                    <span class="glyphicon glyphicon-subscript" ariel-hidden="true"></span>
                                    <p class="glyphicon-class">长文</p>
                                </a>
                            </div>
                        </el-col>
                        <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                            <div>
                                <a class="ep-draggable-item" tid="defaultModule.table" style>
                                    <span class="glyphicon glyphicon-th" ariel-hidden="true"></span>
                                    <p class="glyphicon-class">表格</p>
                                </a>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row style="height: 100px;">
                        <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                            <div>
                                <a class="ep-draggable-item" tid="defaultModule.html" style="">
                                    <span class="glyphicon glyphicon-header" ariel-hidden="true"></span>
                                    <p class="glyphicon-class">html</p>
                                </a>
                            </div>
                        </el-col>
                        <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                            <div>
                                <a class="ep-draggable-item" tid="defaultModule.customText" style>
                                    <span class="glyphicon glyphicon-text-width" ariel-hidden="true"></span>
                                    <p class="glyphicon-class">自定义</p>
                                </a>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row class="drag_item_title">辅助</el-row>
                    <el-row style="height: 100px;">
                        <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                            <div>
                                <a class="ep-draggable-item" tid="defaultModule.hline" style>
                                            <span class="glyphicon glyphicon-resize-horizontal"
                                                  ariel-hidden="true"></span>
                                    <p class="glyphicon-class">横线</p>
                                </a>
                            </div>
                        </el-col>
                        <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                            <div>
                                <a class="ep-draggable-item" tid="defaultModule.vline" style>
                                            <span class="glyphicon glyphicon-resize-vertical"
                                                  ariel-hidden="true"></span>
                                    <p class="glyphicon-class">竖线</p>
                                </a>
                            </div>
                        </el-col>
                    </el-row>
                    <el-row style="height: 100px;">
                        <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                            <div>
                                <a class="ep-draggable-item" tid="defaultModule.rect">
                                    <span class="glyphicon glyphicon-unchecked" ariel-hidden="true"></span>
                                    <p class="glyphicon-class">矩形</p>
                                </a>
                            </div>
                        </el-col>
                        <el-col :span="12" class="drag_item_box" tid="defaultModule.text">
                            <div>
                                <a class="ep-draggable-item" tid="defaultModule.oval">
                                    <span class="glyphicon glyphicon-record" ariel-hidden="true"></span>
                                    <p class="glyphicon-class">椭圆</p>
                                </a>
                            </div>
                        </el-col>
                    </el-row>
                </el-col>
            </el-row>
            <el-row v-else>
                <el-col :span="24" class="small-printElement-types"
                        :id="`hiprintEpContainer_${designId}`">
                </el-col>
            </el-row>
        </el-card>
        <el-card class="card-design">
            <div class="card-header" slot="header">
                <el-button-group>
                    <template v-for="(value, type) in paperTypes">
                        <el-button size="small" :type="curPaperType === type ? 'primary' : ''"
                                   @click="setPaper(type,value)" :key="type">
                            {{ type }}
                        </el-button>
                    </template>
                    <el-popover v-model="paperPopVisible" title="设置纸张宽高(mm)" trigger="click">
                        <div>
                            <el-row>
                                <el-col :span="24">
                                    <el-input type="number" v-model="paperWidth"
                                              style=" width: 100px; text-align: center"
                                              placeholder="宽(mm)" :clearable="false" />
                                    <span>~</span>
                                    <el-input type="number" v-model="paperHeight"
                                              style="width: 100px; text-align: center; border-left: 0"
                                              placeholder="高(mm)" :clearable="false" />
                                </el-col>
                            </el-row>
                            <el-button type="primary" style="width: 100%;margin-top: 10px;" @click="otherPaper">确定
                            </el-button>
                        </div>
                        <el-button slot="reference" size="small" :type="'other'===curPaperType?'primary':''">自定义纸张
                        </el-button>
                    </el-popover>
                </el-button-group>
                <el-button size="small" icon="el-icon-zoom-out" @click="changeScale(false)"></el-button>
                <el-input size="small" :value="scaleValueStr" disabled class="scale_input" :clearable="false" />
                <el-button size="small" icon="el-icon-zoom-in" @click="changeScale(true)"></el-button>
                <el-button-group>
                    <el-button size="small" type="primary" @click="rotatePaper()">旋转</el-button>
                    <el-button size="small" type="primary" @click="preView">预览</el-button>
                    <el-button size="small" type="primary" icon="redo" @click="openDialog('import')">更新模板</el-button>
                    <el-button size="small" type="primary" icon="redo" @click="openDialog('export')">导出模板</el-button>
                    <el-popover v-model="clearPopVisible" trigger="click">
                        <p>是否确认清空?</p>
                        <div style="text-align: right; margin: 0">
                            <el-button size="mini" type="text" @click="clearPopVisible = false">取消</el-button>
                            <el-button type="primary" size="mini" @click="clearPaper()">确定</el-button>
                        </div>
                        <el-button slot="reference" size="small" type="danger">清空</el-button>
                    </el-popover>
                </el-button-group>
            </div>
            <div class="hiprint-printTemplate" :id="`hiprint-printTemplate_${designId}`"></div>
        </el-card>
        <el-card class="card-setting">
            <el-row class="hinnn-layout-sider">
                <div :id="`PrintElementOptionSetting_${designId}`"></div>
            </el-row>
        </el-card>
    </div>
</template>

<script>
import './design.css';
import { defaultElementTypeProvider } from '@common/plugins/hiprint';
import panel from './panel'
import Config from "./Config";
import { genPreViewData } from "../print";
import { chooseImage } from "@common/utils/choose";
import upload from "@common/utils/upload";

export default {
    name: "printDesign",
    props: {
        type: {
            type: String,
            default: 'draggable',
        },
        designId: {
            type: String,
            default: 'default',
        },
    },
    data() {
        return {
            deactivated: false,
            curPaper: {
                type: 'A4',
                width: 210,
                height: 296.6
            },
            paperTypes: {
                'A3': {
                    width: 420,
                    height: 296.6
                },
                'A4': {
                    width: 210,
                    height: 296.6
                },
                'A5': {
                    width: 210,
                    height: 147.6
                },
                'B3': {
                    width: 500,
                    height: 352.6
                },
                'B4': {
                    width: 250,
                    height: 352.6
                },
                'B5': {
                    width: 250,
                    height: 175.6
                }
            },
            // 自定义纸张
            paperPopVisible: false,
            // 自定义纸张
            clearPopVisible: false,
            paperWidth: '220',
            paperHeight: '80',
            // 缩放
            scaleValue: 1,
            scaleMax: 5,
            scaleMin: 0.5,
            // 导入导出json
            jsonIn: '',
            jsonOut: '',
            hiPrintTemplate: undefined,
        }
    },
    computed: {
        curPaperType() {
            let type = 'other'
            let types = this.paperTypes
            for (const key in types) {
                let item = types[key]
                let { width, height } = this.curPaper
                if (item.width === width && item.height === height) {
                    type = key
                }
            }
            return type
        },
        scaleValueStr() {
            return `${ (this.scaleValue * 100).toFixed(0) }%`;
        },
    },
    methods: {
        initConfig(hiprint, option = {}) {
            const _this = this;
            if (_this.designId !== option.designId) {
                return;
            }
            let providers = [ new defaultElementTypeProvider() ];
            if (option.providers) {
                providers = option.providers;
            }
            hiprint.init({
                providers,
            });
            // 还原配置
            hiprint.setConfig();
            // 替换配置
            hiprint.setConfig({
                optionItems: [
                    function () {
                        function t() {
                            // json模板 options 对应键值
                            this.name = "scale";
                        }

                        return t.prototype.css = function (t, e) { // t: 元素对象， e 参数值
                            if (t && t.length) {
                                if (e) return t.css('transform', 'scale(' + e + ')');
                            }
                            return null;
                        }, t.prototype.createTarget = function (t, i, e) { //  t: 元素对象，i: 元素options, e: 元素printElementType
                            return this.target = $('<div class="hiprint-option-item">\n        <div class="hiprint-option-item-label">\n        缩放\n        </div>\n        <div class="hiprint-option-item-field">\n        <input type="number" class="auto-submit"/>\n        </div>\n    </div>'), this.target;
                        }, t.prototype.getValue = function () {
                            var t = this.target.find("input").val();
                            if (t) return parseFloat(t.toString());
                        }, t.prototype.setValue = function (t) { //  t: options 对应键的值
                            this.target.find("input").val(t);
                        }, t.prototype.destroy = function () {
                            this.target.remove();
                        }, t;
                    }(),
                    function () {
                        function t() {
                            this.name = "zIndex";
                        }

                        return t.prototype.css = function (t, e) {
                            if (t && t.length) {
                                if (e) return t.css('z-index', e);
                            }
                            return null;
                        }, t.prototype.createTarget = function () {
                            return this.target = $('<div class="hiprint-option-item">\n        <div class="hiprint-option-item-label">\n        元素层级2\n        </div>\n        <div class="hiprint-option-item-field">\n        <input type="number" class="auto-submit"/>\n        </div>\n    </div>'), this.target;
                        }, t.prototype.getValue = function () {
                            var t = this.target.find("input").val();
                            if (t) return parseInt(t.toString());
                        }, t.prototype.setValue = function (t) {
                            this.target.find("input").val(t);
                        }, t.prototype.destroy = function () {
                            this.target.remove();
                        }, t;
                    }(),
                ],
                movingDistance: 2.5,
                text: {
                    tabs: [
                        {
                            name: '基础',
                            options: [
                                {
                                    name: 'scale',
                                    after: 'transform', // 自定义参数，插入在 transform 之后
                                    hidden: false
                                },
                            ]
                        }
                    ],
                    supportOptions: [
                        {
                            name: 'styler',
                            hidden: true
                        },
                        {
                            name: 'scale', // 自定义参数，supportOptions 必须得添加
                            after: 'transform', // 自定义参数，插入在 transform 之后
                            hidden: false
                        },
                        {
                            name: 'formatter',
                            hidden: true
                        },
                    ]
                },
            })
            // eslint-disable-next-line no-undef
            if (_this.type === 'draggable') {
                hiprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'));
            } else if (_this.$utils.isNotEmpty(option.module)) {
                let container = $(_this.getActiveTabsContainer()).find(`#hiprintEpContainer_${ option.designId }`);
                container.empty();
                hiprint.PrintElementTypeManager.build(container, option.module);
            }
            $(`#hiprint-printTemplate_${ option.designId }`).empty();
            _this.hiPrintTemplate = new hiprint.PrintTemplate({
                template: option.template ? option.template : panel,
                // 图片选择功能
                onImageChooseClick: _this.onImageChooseClick,
                // 自定义可选字体
                // 或者使用 _this.hiPrintTemplate.setFontList([])
                // 或元素中 options.fontList: []
                fontList: [
                    { title: '微软雅黑', value: 'Microsoft YaHei' },
                    { title: '黑体', value: 'STHeitiSC-Light' },
                    { title: '思源黑体', value: 'SourceHanSansCN-Normal' },
                    { title: '宋体', value: 'SimSun' },
                    { title: '华为楷体', value: 'STKaiti' },
                    { title: 'cursive', value: 'cursive' },
                ],
                dataMode: 1, // 1:getJson 其他：getJsonTid 默认1
                history: true, // 是否需要 撤销重做功能
                onDataChanged: (type, json) => {
                    console.log(type); // 新增、移动、删除、修改(参数调整)、大小、旋转
                    console.log(json); // 返回 template
                },
                onUpdateError: (e) => {
                    console.log(e);
                },
                settingContainer: `#PrintElementOptionSetting_${ option.designId }`,
                paginationContainer: `.hiprint-printPagination_${ option.designId }`
            });
            let designContainer = $(_this.getActiveTabsContainer()).find(`#hiprint-printTemplate_${ option.designId }`);
            designContainer.empty();
            _this.hiPrintTemplate.design(`#hiprint-printTemplate_${ option.designId }`, {
                grid: true,
            });
            // 获取当前放大比例, 当zoom时传true 才会有
            this.scaleValue = _this.hiPrintTemplate.editingPanel.scale || 1;
            let paperType = _this.hiPrintTemplate.editingPanel.paperType;
            this.curPaper = {
                width: _this.hiPrintTemplate.editingPanel.width,
                height: _this.hiPrintTemplate.editingPanel.height,
            };
            if (!paperType) {
                this.paperWidth = _this.hiPrintTemplate.editingPanel.width;
                this.paperHeight = _this.hiPrintTemplate.editingPanel.height;
            }
        },
        onImageChooseClick(target) {
            const _this = this;
            chooseImage().then(base64 => {
                upload.uploadBase64Slice({
                    base64,
                    associate_biz_table: 'base_print_design',
                    associate_biz_sid: _this.designId,
                    associate_biz_field_tag: 'template_json',
                }).then(res => {
                    let resData = res.data || {};
                    if (_this.$utils.isNotEmpty(resData.sid)) {
                        let url = window.configs.requestPrefix + _this.$api.File_GetFile
                            + _this.$utils.getAccountSetSidEndWithSlash() + resData.sid;
                        target.refresh(url, {
                            // auto: true, // 根据图片宽高自动等比(宽>高?width:height)
                            // width: true, // 按宽调整高
                            // height: true, // 按高调整宽
                            real: true // 根据图片实际尺寸调整(转pt)
                        });
                    }
                }).catch(() => {
                    _this.$message.error("上传失败");
                });
            });
        },
        /**
         * 设置纸张大小
         * @param type [A3, A4, A5, B3, B4, B5, other]
         * @param value {width,height} mm
         */
        setPaper(type, value) {
            const _this = this;
            try {
                if (Object.keys(this.paperTypes).includes(type)) {
                    this.curPaper = { type: type, width: value.width, height: value.height }
                    _this.hiPrintTemplate.setPaper(value.width, value.height)
                } else {
                    this.curPaper = { type: 'other', width: value.width, height: value.height }
                    _this.hiPrintTemplate.setPaper(value.width, value.height)
                }
            } catch (error) {
                this.$message.error(`操作失败: ${ error }`)
            }
        },
        otherPaper() {
            let value = {}
            value.width = this.paperWidth
            value.height = this.paperHeight
            this.paperPopVisible = false
            this.setPaper('other', value);
        },
        changeScale(big) {
            const _this = this;
            let scaleValue = _this.scaleValue;
            if (big) {
                scaleValue += 0.1;
                if (scaleValue > _this.scaleMax) scaleValue = 5;
            } else {
                scaleValue -= 0.1;
                if (scaleValue < _this.scaleMin) scaleValue = 0.5;
            }
            if (hiprintTemplate) {
                // scaleValue: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
                _this.hiPrintTemplate.zoom(scaleValue);
                _this.scaleValue = scaleValue;
            }
        },
        rotatePaper() {
            const _this = this;
            if (_this.hiPrintTemplate) {
                _this.hiPrintTemplate.rotatePaper();
            }
        },
        preView() {
            const _this = this;
            if (!_this.hiPrintTemplate) {
                return;
            }
            let preData = genPreViewData(_this.hiPrintTemplate);
            _this.$PrintPreview({
                template: _this.hiPrintTemplate.getJson(),
                data: preData,
                preview: true,
            });
        },
        openDialog(type) {
            const _this = this;
            let title = '更新模板';
            let propsData = {
                json: '',
            };
            if (type === 'export') {
                title = '导出模板';
                if (_this.hiPrintTemplate) {
                    propsData = {
                        json: JSON.stringify(_this.hiPrintTemplate.getJson() || {}),
                    };
                }
            }
            _this.$dialog({
                width: '500px',
                title,
                component: {
                    value: Config,
                    props: {
                        propsData,
                    },
                },
                hideConfirmBtn: type === 'export',
                confirmBtn: {
                    type: 'primary',
                    text: '确定',
                    click(dialog, { component }) {
                        _this.updateTemplate(component.json);
                        dialog.visible = false;
                    },
                },
            });
        },
        updateTemplate(json) {
            const _this = this;
            if (_this.$utils.isNotEmpty(json) && _this.hiPrintTemplate) {
                try {
                    _this.hiPrintTemplate.update(JSON.parse(json))
                } catch (e) {
                    _this.$message.error(`更新失败: ${ e }`)
                }
            }
        },
        getTemplateJson() {
            const _this = this;
            if (_this.hiPrintTemplate) {
                return _this.hiPrintTemplate.getJson() || {};
            }
            return {};
        },
        clearPaper() {
            const _this = this;
            try {
                _this.hiPrintTemplate.clear();
            } catch (error) {
                _this.$message.error(`操作失败: ${ error }`);
            }
            _this.clearPopVisible = false;
        },
    }
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
@import "../../../plugins/hiprint/css/glyphicon.css";

.design_container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;

    .card_draggable {
        flex: 4;

        /deep/ .drag_item_title {
            font-size: 16px;
            padding: 12px 6px 0 6px;
            font-weight: bold;
        }

        // 拖拽
        /deep/ .drag_item_box {
            height: 100%;
            padding: 6px;

            div {
                height: 100%;
                width: 100%;
                background-color: #fff;
                display: flex;
                justify-content: center;
                align-items: center;

                a {
                    text-align: center;
                    color: #1890ff;
                    background-color: transparent;
                    outline: none;
                    cursor: pointer;
                    text-decoration-line: none;

                    span {
                        font-size: 28px;
                    }

                    p {
                        margin: 0;
                        font-size: 14px;
                    }
                }
            }
        }
    }

    .card-design {
        flex: 15;
        margin: 0 8px;
        overflow: hidden;

        /deep/ .scale_input {
            width: 80px;
            height: auto !important;

            input {
                text-align: center;
            }
        }

        /deep/ .el-card__body {
            padding: 15px;
            width: 100%;
            height: calc(100% - 45px);
            overflow: auto;
        }
    }

    .card-setting {
        flex: 5;
    }
}
</style>
